package com.sondon.mayi.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sondon.mayi.activity.AddressManagerActivity_;
import com.sondon.mayi.activity.CartActivity_;
import com.sondon.mayi.activity.ConfigActivity;
import com.sondon.mayi.activity.ConfigActivity_;
import com.sondon.mayi.activity.LoginActivity_;
import com.sondon.mayi.activity.MyChat_;
import com.sondon.mayi.activity.MyScoreActivity_;
import com.sondon.mayi.activity.MyVoucherActivity_;
import com.sondon.mayi.activity.NoticeActivity_;
import com.sondon.mayi.activity.SetPasswdActivity_;
import com.sondon.mayi.configs.URLConfigs;
import com.sondon.mayi.entity.ContactEntity;
import com.sondon.mayi.entity.MyInfoEntity;
import com.sondon.mayi.entity.RespondBaseEntity;
import com.sondon.mayi.events.TabHostChangeEvent;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.ui.CircularImage;
import com.sondon.mayi.ui.MyMultipleTopBar;
import com.sondon.mayi.ui.PicturePopClickListener;
import com.sondon.mayi.ui.Picture_PopupWindows;
import com.sondon.mayi.ui.TopBarClickListener;
import com.sondon.mayi.util.AsyncHttpUtil;
import com.sondon.mayi.util.GsonUtil;
import com.sondon.mayi.util.ImageLoaderUtil;
import com.sondon.mayi.util.ImageUtils;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.MyAlertDialog;
import com.sondon.mayi.util.ShareUtil;
import com.sondon.mayi.util.ToastUtils;

import de.greenrobot.event.EventBus;

@SuppressLint("HandlerLeak")
@EFragment(R.layout.my)
public class MyFragmentPage extends BaseFragment {
	@ViewById
	MyMultipleTopBar topBar;// 标题 
	@ViewById
	LinearLayout upgrade_outer;//头部layout
	@ViewById
	LinearLayout myvoucher;// 我的现金券
	@ViewById
	LinearLayout myscore;// 我的积分
	@ViewById
	LinearLayout upgrade_msg_box;// 升级会员
	@ViewById
	CircularImage  face;// 头像
	@ViewById
	TextView username;// 用户名(手机号)
	@ViewById
	ImageView rank_pic;// 等级头像
	@ViewById
	TextView rank;// 等级
	@ViewById
	TextView upgrade;// 等级升级
	@ViewById
	LinearLayout you_not_login;// 没有登录
	@ViewById
	LinearLayout upload_contact_box;//上传更新通讯录
	@ViewById
	LinearLayout addr_man;// 收货地址管理
	@ViewById
	LinearLayout passwd_box;// 密码设置
	@ViewById
	LinearLayout config;// 设置
	@ViewById
	LinearLayout share;// 分享
	@ViewById
	TextView kfphone;// 客服电话
	@ViewById
	Button logout;// 登出

	private AsyncQueryHandler asyncQuery;
	private List<ContactEntity> contactList;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;
	
	@AfterViews
	public void initView() {
		// ToastUtils.show(getActivity(), R.string.processing);

		// topbar的监听事件
		topBar.setTopBarClickListener(new TopBarClickListener() {

			@Override
			public void rightBtnClick() {
				// 购物车
				openActivity(CartActivity_.class);
			}

			@Override
			public void leftBtnClick() {
				// 动态消息
				openActivity(NoticeActivity_.class);
			}
		});

		if (!myprefs.is_login().get()) {
			//没有登陆过
			upgrade_msg_box.setVisibility(View.GONE);
			face.setVisibility(View.GONE);
			you_not_login.setVisibility(View.VISIBLE);
//			upgrade_outer.setBackgroundColor(getResources().getColor(R.color.topbar_backage_color));
		} else {
			//已经登陆过
			upgrade_msg_box.setVisibility(View.VISIBLE);
			face.setVisibility(View.VISIBLE);
			you_not_login.setVisibility(View.GONE);
//			upgrade_outer.setBackgroundColor(getResources().getColor(R.color.backage_color));
			
			//获取个人信息
			AsyncHttpUtil.get(URLConfigs.MyInfo_ukey+myprefs.Ukey().get(), null, new TextHttpResponseHandler() {
				
				@Override
				public void onSuccess(int status, Header[] arg1, String json) {
					if(200==status){
					LogUtil.e(TAG, "获取个人信息  json ："+json);
					MyInfoEntity entity=GsonUtil.GetFromJson(json, MyInfoEntity.class);
					if(entity.isStatus()){
						//保存头像地址
						myprefs.head_img().put(entity.getInfo().getHead_ico());
						//加载图片
						ImageLoaderUtil.SetImgView(entity.getInfo().getHead_ico(), face);
						ImageLoaderUtil.SetImgView(entity.getInfo().getPic(), rank_pic);
						
						username.setText(entity.getInfo().getUsername());
						rank.setText(entity.getInfo().getGroup_name());
						upgrade.setText(entity.getInfo().getGroup_msg());
						
					}else{
						
						}
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					ToastUtils.show(getActivity(), R.string.network_unavailable);
				}
			});
		}
		
		//设置客服电话
		kfphone.setText(myprefs.custom_phone().get());
		
		// 获取通讯录里的联系人
		asyncQuery = new MyAsyncQueryHandler(getActivity().getContentResolver());
		initContacts();
	}

	@Override
	public void onResume() {
		
		super.onResume();
		//设置消息
		String news_code=myprefs.news_code().get();
		if("0".equals(news_code)){
			topBar.setNoticeNews(true);
		}else{
			topBar.setNoticeNews(false);
		}
	}
	
	@Click({ R.id.myvoucher, R.id.myscore, R.id.mychat, R.id.logout,
			R.id.version_box, R.id.upload_head_pic_box, R.id.modify_region_box,
			R.id.upload_contact_box, R.id.addr_man, R.id.passwd_box,
			R.id.share, R.id.you_not_login, R.id.config,R.id.face })
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.face:
			// 选择图片来源：相册或者照相机
			final Picture_PopupWindows picture_pop=new Picture_PopupWindows(getActivity(), upgrade_outer);
			picture_pop
			 	 .SetPictureOnClickListener(new PicturePopClickListener() {
				
				@Override
				public void PopPhotoClick() {
					openAlbum();
					picture_pop.dismiss();
				}
				
				@Override
				public void PopCameraClick() {
					camera();
					picture_pop.dismiss();
				}
			});
			break;
		case R.id.myvoucher:// 现金券
			openActivity_Login(MyVoucherActivity_.class);
			break;
		case R.id.myscore:// 积分和等级
			openActivity_Login(MyScoreActivity_.class);
			break;
		case R.id.mychat:// 我的聊天
			openActivity_Login(MyChat_.class);
			break;
		case R.id.you_not_login:// 没有登录
			openActivity(LoginActivity_.class);
			break;
		case R.id.upload_contact_box:// 上传通讯录
			if(myprefs.is_login().get()){
				MyAlertDialog.show(getActivity(), "通讯录", "是否上传通讯录到服务器 ?", "NO","YES");
				//左边按钮监听事件
				OnClickListener	 leftListener=new OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										if(MyAlertDialog.getMydialog().isShowing()){
											MyAlertDialog.getMydialog().dismiss();
										}
									}
								};
				//右边按钮监听事件
				OnClickListener	 rightListener=new OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										if(MyAlertDialog.getMydialog().isShowing()){
											MyAlertDialog.getMydialog().dismiss();
											UploadContacts();
										}
									}
								};
				//设置监听事件
				MyAlertDialog.setLeftRightListener(leftListener, rightListener);
				
				
			}else{
				ToastUtils.show(getActivity(), "请登录!");
			}
			
			break;
		case R.id.addr_man:// 添加收货地址
			openActivity_Login(AddressManagerActivity_.class);
			break;
		case R.id.passwd_box:// 设置密码
			openActivity_Login(SetPasswdActivity_.class);
			break;
		case R.id.share://我的分享
//			openActivity(ShareActivity_.class);
			ShareUtil.ShareSDK(getActivity());
			break;
		case R.id.config:// 设置
			openActivity(ConfigActivity_.class);
			break;
		case R.id.logout:// 登出
			myprefs.clear();
//			openActivity(MainTabActivity_.class);
			EventBus.getDefault().post(new TabHostChangeEvent(0));
			break;
		default:
			break;
		}
	}

	/******************************************************** 上传通讯录 **********************************************************/
	public void UploadContacts() {
		// 获取联系人
		initContacts();
		// [{"name":"test","phone":"123456"},{"name":"test1","phone":"123452"}]
		LogUtil.e(TAG, "联系人  ：" + GsonUtil.ObjectToJson(contactList));
		// 设置参数,发送请求
		RequestParams params = new RequestParams();
		params.put("str", GsonUtil.ObjectToJson(contactList));
		AsyncHttpUtil.post(
			URLConfigs.UploadContact_ukey + myprefs.Ukey().get(), params,
			new TextHttpResponseHandler() {

				@Override
				public void onSuccess(int statue, Header[] header,
						String json) {
					LogUtil.e(TAG, "UploadContact  json :" + json);
					if (statue == 200) {
						RespondBaseEntity res = GsonUtil.GetFromJson(json,
								RespondBaseEntity.class);
						
						if (res.isStatus()) {
							ToastUtils.show(getActivity(), res.getMsg());
						} else {
							ToastUtils.show(getActivity(), res.getMsg());
						}

					}
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2,
						Throwable e) {
					ToastUtils.show(getActivity(), R.string.network_unavailable);
					e.printStackTrace();
				}

			});
	}

	/**
	 * 
	 * @Author 蔡文锋
	 * @Data_Time 2015-6-12 下午2:41:37
	 * @Description { 初始化联系人查询 }
	 */
	private void initContacts() {
		// 联系人的Uri
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		// 查询的列
		String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
				ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY };

		// 按照sort_key升序查询
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				"sort_key COLLATE LOCALIZED asc");
	}

	/**
	 * 
	 * @Project : Fruit
	 * @Package : com.sondon.mayi.fragment
	 * @Class : ConfigFragmentPage.java
	 * @Author : 蔡文锋
	 * @DateTime：2015-6-12 下午4:35:24
	 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
	 * @Description : {数据库异步查询类AsyncQueryHandler}
	 */
	private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
		}

		/**
		 * 查询结束的回调函数
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {

				contactList = new ArrayList<ContactEntity>();
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					ContactEntity cb = new ContactEntity();

					cursor.moveToPosition(i);
					String name = cursor.getString(1);
					String number = cursor.getString(2);
					// String sortKey = cursor.getString(3);
					// int contactId = cursor.getInt(4);
					// Long photoId = cursor.getLong(5);
					// String lookUpKey = cursor.getString(6);

					cb.setName(name);
					cb.setPhone(number);
					// cb.setSortKey(sortKey);
					// cb.setContactId(contactId);
					// cb.setPhotoId(photoId);
					// cb.setLookUpKey(lookUpKey);

					contactList.add(cb);
				}
			}
		}
	}

	

	/******************************************************* 拍照 相册 *************************************************************/

	private static String picFileFullName;

	// 拍照
	public void camera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File outDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			if (!outDir.exists()) {
				outDir.mkdirs();
			}
			File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
			picFileFullName = outFile.getAbsolutePath();
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
		} else {
			Log.e(TAG, "请确认已经插入SD卡");
		}
	}

	// 打开本地相册
	public void openAlbum() {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_PICK);

		intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, PICK_IMAGE_ACTIVITY_REQUEST_CODE);

		// Intent intent = new Intent();
		// intent.setType("image/*");
		// intent.setAction(Intent.ACTION_GET_CONTENT);
		// this.startActivityForResult(intent,
		// PICK_IMAGE_ACTIVITY_REQUEST_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == ConfigActivity.RESULT_OK) {
				Log.e(TAG, "获取图片成功，path=" + picFileFullName);
				setImageView(picFileFullName);
			} else if (resultCode == ConfigActivity.RESULT_CANCELED) {
				// 用户取消了图像捕获
			} else {
				// 图像捕获失败，提示用户
				Log.e(TAG, "拍照失败");
				ToastUtils.show(context, "拍照失败");
			}
		} else if (requestCode == PICK_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == ConfigActivity.RESULT_OK) {
				Uri uri = data.getData();
				if (uri != null) {
					String realPath = getRealPathFromURI(uri);
					Log.e(TAG, "获取图片成功，path=" + realPath);
					setImageView(realPath);
				} else {
					Log.e(TAG, "从相册获取图片失败");
					ToastUtils.show(context, "从相册获取图片失败");
				}
			}
		}
	}

	private void setImageView(String realPath) {
//		Bitmap bmp = BitmapFactory.decodeFile(realPath);
//		LogUtil.e(TAG, "普通获取bitmap  byteCount :"+bmp.getByteCount());
		File imgFile=new File(realPath);
		LogUtil.e(TAG, "imgFile size :"+imgFile.length());
		Bitmap bmp=ImageUtils.compressImageFromFile(realPath,250,250);
		LogUtil.e(TAG, "工具类获取bitmap  byteCount :"+bmp.getByteCount());
		
		int degree = readPictureDegree(realPath);
		if (degree <= 0) {
			face.setImageBitmap(bmp);
		} else {
			Log.e(TAG, "rotate:" + degree);
			// 创建操作图片是用的matrix对象
			Matrix matrix = new Matrix();
			// 旋转图片动作
			matrix.postRotate(degree);
			// 创建新图片
			Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0,
					bmp.getWidth(), bmp.getHeight(), matrix, true);
			face.setImageBitmap(resizedBitmap);
		}
		
		//上传图片1
//		byte[] img_byte=ImageUtils.bitmapToByte(bmp);
//		RequestParams params = new RequestParams();
//		params.put("file", new ByteArrayInputStream(img_byte), "mayi.png");
//		AsyncHttpUtil.post(URLConfigs.UploadHeadImage_ukey+myprefs.Ukey().get(), params, new TextHttpResponseHandler() {
//			
//			@Override
//			public void onSuccess(int status, Header[] arg1, String json) {
//				LogUtil.e(TAG, "上传图片  json :"+json);
//			}
//			
//			@Override
//			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//			}
//		});
		//上传图片2
		RequestParams params = new RequestParams();
		//判断文件是否存在
		if (!imgFile.exists()) {
			ToastUtils.show(context, "文件已经不存在！");
			return;
		}
		try {
			params.put("attach", imgFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		AsyncHttpUtil.post(URLConfigs.UploadHeadImage_ukey+myprefs.Ukey().get(), params, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int status, Header[] arg1, String json) {
				LogUtil.e(TAG, "上传图片  json :"+json);
				RespondBaseEntity entity=GsonUtil.GetFromJson(json, RespondBaseEntity.class);
				if(entity.isStatus()){
					ToastUtils.show(context, entity.getMsg());
				}else{
					ToastUtils.show(context, entity.getMsg());
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				ToastUtils.show(context, R.string.network_unavailable);
			}
		});
	}

	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			// Do not call Cursor.close() on a cursor obtained using this
			// method,
			// because the activity will do that for you at the appropriate time
			@SuppressWarnings("deprecation")
			Cursor cursor = ((Activity) context).managedQuery(contentUri, proj, null,null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 读取照片exif信息中的旋转角度<br/>
	 * http://www.eoeandroid.com/thread-196978-1-1.html
	 * 
	 * @param path
	 *            照片路径
	 * @return角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	
}